
import * as React from "react";
import { ISignPosition } from "MyTypes";
import { drawImage, drawRect } from "../../util/canvasTool";
import { genSignInitState, createImage, isPC, noop, getUrlParam } from "../../util/help";
import { PDFDocument, rgb } from "pdf-lib";
//import download from 'downloadjs';

const { useCallback, useState } = React;

export const useEditPdf = (
  curPdfCanvas: HTMLCanvasElement,
  isPdfEndLoadRef: React.MutableRefObject<boolean>) => {
  const [selectSign, saveSelectSign] = useState<ISignPosition | undefined>();
  const [signList, updateSignList] = useState<ISignPosition[]>([]);
  const [pdfReadBuffer, savePdfReadBuffer] = useState<ArrayBuffer | null>(null);
  const [fileName, setFileName] = useState<string>('');
  // 添加签名
  const addSignInCanvas = useCallback((
    signSrc: string,
    w: number,
    h: number
  ) => {

    //console.log('测试')
    //console.log(curPdfCanvas)
    if (!curPdfCanvas) {
      alert('请先点击文件以确认签名位置!')
      return;
    };
    const image = createImage(signSrc);
    const signPosition = genSignInitState() as ISignPosition;

    let newSignList = [...signList]
    newSignList.push({
      ...signPosition,
      image,
      pdfCanvas: curPdfCanvas,
      signSrc,
      w,
      h,
      pageIndex: +(curPdfCanvas.getAttribute('pageindex') as string),
      signType: 'image'
    });
    //console.log('newSignList', newSignList);
    updateSignList([...newSignList]);
  }, [signList, curPdfCanvas, selectSign]);

  // 删除签名
  const deleteSignInCanvas = useCallback(() => {
    const deleteSignList = signList.filter((sign) => {
      if (selectSign) {
        const isDelete = sign.id === selectSign.id;
        if (isDelete) {
          return !isDelete;
        }
        return sign.signType !== 'rectTool';
      }
      return false;
    });
    updateSignList(deleteSignList);
  }, [selectSign, signList]);
  // 下载pdf
  const downloadPdf = useCallback(async () => {

    //console.log('下载pdf')

    if (!pdfReadBuffer) {
      return
    }

    const newPdfDoc = await PDFDocument.load(pdfReadBuffer as ArrayBuffer);

    const pagesProcesses = newPdfDoc.getPages().map(async (page, pageIndex) => {
      const { width, height } = page.getSize();
      const signs = signList.filter((sign) => sign.pageIndex === pageIndex);
      const drawIntoPageTask = signs.map(async (sign) => {
        let { signSrc, x, y, w, h, pdfCanvas } = sign;
        const scale = pdfCanvas.width / width;
        const ex = x / scale;
        const ey = y / scale;
        try {
          let img = await newPdfDoc.embedPng(signSrc as string);

          //const font = await newPdfDoc.embedFont(await newPdfDoc.createFont('Helvetica'));

          const addDate = getUrlParam("date");

          if (addDate) {
            const now = new Date();
            const dateStr = now.toLocaleDateString();
            //const dateStr = formatDateTime(now);

            page.drawText(dateStr, {
              x: ex, // X坐标
              y: height - ey - h / scale - 10, // Y坐标（从顶部向下）
              size: 10, // 字体大小
              //font, // 使用的字体
              color: rgb(1, 0, 0) // 字体颜色（黑色）
            });
          }

          return () => page.drawImage(img, {
            x: ex,
            y: height - ey - h / scale,
            width: w / scale,
            height: h / scale,
          });
        } catch (e) {
          console.log('签名图片加载失败', e);
          return noop;
        }
      });
      const drawProcesses = await Promise.all(drawIntoPageTask);
      drawProcesses.forEach((p) => p());
    });

    await Promise.all(pagesProcesses);
    const pdfBytes = await newPdfDoc.save();

    //download(pdfBytes, 'download', 'application/pdf');

    let signUrl = '';
    //let oriUrl = '';

    const signBlob = new Blob([pdfBytes], { type: 'application/pdf' });
    //const oriBlob = new Blob([pdfReadBuffer!], { type: 'application/pdf' });

    // @ts-ignore
    if (window.createObjectURL != undefined) {
      // @ts-ignore
      signUrl = window.createObjectURL(signBlob);
      // @ts-ignore
      //oriUrl = window.createObjectURL(oriBlob);
    } else if (window.URL != undefined) {
      signUrl = window.URL.createObjectURL(signBlob);
      //oriUrl = window.URL.createObjectURL(oriBlob);
    } else if (window.webkitURL != undefined) {
      signUrl = window.webkitURL.createObjectURL(signBlob);
      //oriUrl = window.webkitURL.createObjectURL(oriBlob);
    }

    localStorage.setItem('pdf-download', JSON.stringify({
      name: fileName,
      //ori_url: oriUrl,
      sign_url: signUrl
    }))

    window.parent.postMessage({
      type: 'pdf-download',
      data: pdfBytes
    }, '*');

    localStorage.setItem('pdf-download-state', '1')
    //alert('签名成功!');
    //download(pdfBytes, 'download', 'application/pdf');
  }, [pdfReadBuffer, signList, fileName]);

  // 上传pdf
  const uploadPdf = useCallback(async (e: any) => {
    if (e.target.files) {
      const file = e.target.files[0];
      const arrayBuffer = await file.arrayBuffer();
      savePdfReadBuffer(arrayBuffer);
      setFileName(file.name)
      isPdfEndLoadRef.current = false;
    }
  }, []);

  // TOOD:上传签名
  const uploadSign = useCallback(async (e: any) => {

    // if (e.target.files) {
    //   const file = e.target.files[0];

    //   if (file) {
    //     const reader = new FileReader();
    //     reader.readAsDataURL(file);

    //     reader.onload = function(e) {

    //       const dataURL = e.target!.result as any;

    //       // 上传签名
    //       addSignInCanvas(dataURL, 250, 80);

    //     };

    // }



    //   //savePdfReadBuffer(arrayBuffer);
    //   //isPdfEndLoadRef.current = false;
    // }

    const data = localStorage.getItem('ZDFMS_usersign')
    const dataURL = "data:image/png;base64," + data;
    addSignInCanvas(dataURL, 250, 80);

  }, [curPdfCanvas]);

  return {
    uploadSign,
    addSignInCanvas, deleteSignInCanvas, downloadPdf, uploadPdf,
    saveSelectSign,
    signList, updateSignList, pdfReadBuffer, savePdfReadBuffer
  }
}
